package platform.standard.video;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import engine.Constants;

public class ScreenComponent extends Canvas {
	private static final long serialVersionUID = 1L;
	public ScreenComponent(AwtScreenBuffer buffer) {
		_Buffer = buffer;
		this.setIgnoreRepaint(true);
		this.setVisible(true);
	}

	/**
	 * Initializes the back buffer.
	 **/
	public void initGraphics() {
		this.createBufferStrategy(2);
		_Strategy = this.getBufferStrategy();
		resetGraphics();
	}

	/**
	 * Resets the back buffer if it gets lost.
	 **/
	public void resetGraphics() {
		if (_DrawGraphics != null) {
			_DrawGraphics.dispose();
		}
		_DrawGraphics = _Strategy.getDrawGraphics();
	}

	/**
	 * Copies the game screen into the back buffer, performing any necessary
	 * scaling, then displays it.
	 **/
	public void render() {
		if (_Strategy == null) {
			initGraphics();
		}
		if (_Strategy.contentsLost()) {
			resetGraphics();
		}
		float w = this.getParent().getWidth();
		float h = this.getParent().getHeight();
		if(w > h) {
			w = (h / Constants.SCREEN_ASPECT_RATIO) + 0.5f;
		} else {
			h = (w * Constants.SCREEN_ASPECT_RATIO) + 0.5f;
		}
		_DrawGraphics.drawImage(_Buffer.getImage(), 0, 0, (int)w,
				(int)h, null);
		_Strategy.show();
	}
	
	public AwtScreenBuffer getScreenBuffer() {
		return _Buffer;
	}

	@Override
	public void paint(Graphics g) {
		// Overridden intentionally to do nothing.
	}

	private AwtScreenBuffer _Buffer;
	private BufferStrategy _Strategy;
	private Graphics _DrawGraphics;
}
